package view;

import MySQL.MySQL_Product;
import MySQL.MySQL_Sale;
import back.Head;
import back.Product;
import back.Sale;
import back.User;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

import static back.Head.*;

public class Manager {
    private JPanel panel =  new JPanel();
    private CardLayout cardLayout = new CardLayout();
    private JPanel cardPanel = new  JPanel(cardLayout);

    private JPanel checkoutPanel = new  JPanel();
    private JPanel productPanel = new  JPanel();
    private JPanel userPanel = new  JPanel();
    private JPanel salesPanel = new  JPanel();

    private JButton checkoutButton = new JButton("结账服务");
    private JButton productButton = new JButton("商品管理");
    private JButton userButton = new JButton("用户管理");
    private JButton salesButton = new JButton("销售统计");
    private JButton exitButton = new JButton("退出登录");

    public  Manager() {
        panel.setLayout(new BorderLayout(0,50));
        panel.add(createNorth(),BorderLayout.NORTH);
        panel.add(cardPanel,BorderLayout.CENTER);
        cardLayout.show(cardPanel,"checkout");
        setCardPanel();
        setupListeners();
    }
    public JPanel GetPanel(){
        return panel;
    }
    private JPanel createNorth(){
        JPanel north = new JPanel();
        north.add(checkoutButton);
        north.add(productButton);
        north.add(userButton);
        north.add(salesButton);
        north.add(exitButton);
        north.setLayout(new FlowLayout(FlowLayout.LEFT,0,0));
        return north;
    }
    private void setCardPanel(){
        checkoutPanel = createCheckout();
        productPanel = createProductPanel();
        userPanel = createUserPanel();
        salesPanel = createSalesPanel();

        // 添加到卡片面板
        cardPanel.add(checkoutPanel, "checkout");
        cardPanel.add(productPanel, "product");
        cardPanel.add(userPanel, "user");
        cardPanel.add(salesPanel, "sales");
    }

    private JPanel createCheckout(){
        checkoutPanel.setLayout(new BorderLayout());
        JPanel leftPanel = new JPanel();
        JPanel rightPanel = new JPanel();

        JLabel titleLabel = new JLabel("结账服务系统", JLabel.CENTER);

        JTextField commodityTF = new JTextField(16);
        JTextField buyTF = new JTextField(8);
        JButton commodity = new JButton("查询");
        JButton buy = new JButton("加购");
        JLabel hint = new JLabel("……");
        JButton remove = new JButton("移除商品");
        JButton clear = new JButton("清空购物车");
        final int[] N1 = {0};
        final double[] N2 = {0};
        JLabel piecesNumber = new JLabel("件数：" + N1[0]);
        JLabel total = new JLabel("合计：" + N2[0] + "元");
        JButton checkout = new JButton("结账");

        leftPanel.setLayout(new GridLayout(8,1,0,0));
        JPanel left_1 = new JPanel();
        JPanel left_2 = new JPanel();
        JPanel left_3 = new JPanel();

        left_1.add(new JLabel("商品编号"));
        left_1.add(commodityTF);
        left_1.add(commodity);
        left_1.add(new JLabel("数量"));
        left_1.add(buyTF);
        left_1.add(buy);

        left_2.add(remove);
        left_2.add(clear);

        left_3.add(checkout);

        leftPanel.add(left_1);
        leftPanel.add(hint);
        leftPanel.add(left_2);
        leftPanel.add(piecesNumber);
        leftPanel.add(total);
        leftPanel.add(left_3);


        String[] columns = {"商品编号", "商品名称", "价格", "数量"};
        DefaultTableModel model = new DefaultTableModel(columns, 0) {
            @Override
            public Class<?> getColumnClass(int columnIndex) {
                switch (columnIndex) {
                    case 0: return String.class;  // 商品编号
                    case 1: return String.class;  // 商品名称
                    case 2: return Double.class;  // 价格
                    case 3: return Integer.class; // 数量
                    default: return Object.class;
                }
            }
            @Override
            public boolean isCellEditable(int row, int column) {
                return column == 3;
            }
        };

        JTable table = new JTable(model);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane scrollPane = new JScrollPane(table);
        rightPanel.add(scrollPane);
        rightPanel.setLayout(new FlowLayout(FlowLayout.CENTER,0,0));

        checkoutPanel.add(titleLabel, BorderLayout.NORTH);
        checkoutPanel.add(leftPanel, BorderLayout.CENTER);
        checkoutPanel.add(rightPanel, BorderLayout.WEST);
        commodity.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Product product = mySQL_Product.getProductByIP(commodityTF.getText());
                hint.setText(product.getName() + " 价格：" + product.getPrice() + " 数量：" +  product.getAmount());
            }
        });
        buy.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Product product = mySQL_Product.getProductByIP(commodityTF.getText());
                if(isInteger(buyTF.getText())){
                    product.setAmount(Integer.parseInt(buyTF.getText()));
                    model.addRow(product.toArray());
                    hint.setText("添加成功！");
                    N1[0] += product.getAmount();
                    N2[0] += product.getPrice()*product.getAmount();
                    piecesNumber.setText("件数：" + N1[0]);
                    total.setText("合计：" + N2[0] + "元");
                }
            }
        });
        remove.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int selectedRow = table.getSelectedRow();
                if (selectedRow != -1) {
                    int modelRow = table.convertRowIndexToModel(selectedRow);
                    model.removeRow(modelRow);
                }else{
                    JOptionPane.showMessageDialog(left_2, "请先选择要删除的行");
                }
            }
        });
        clear.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                model.setRowCount(0);
            }
        });
        checkout.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                LocalDate currentDate = LocalDate.now();
                if(N1[0] != 0){
                    int rowCount = table.getRowCount();
                    JDialog dialog = new JDialog();
                    JPanel panel = new JPanel();
                    JPanel panel_1 = new JPanel();
                    JLabel price =  new JLabel("共计" + N2[0] + "元");
                    JLabel remin =  new JLabel("请输入支付金额：");
                    JTextField priceTF = new JTextField(12);
                    JButton re = new JButton("确认支付");
                    dialog.setBounds(700, 200, 300, 400);
                    dialog.setLayout(new FlowLayout(FlowLayout.CENTER,0,50));
                    panel.setLayout(new GridLayout(3,1,0,20));
                    panel.add(price);
                    panel_1.add(remin);
                    panel_1.add(priceTF);
                    panel.add(panel_1);
                    panel.add(re);
                    dialog.add(panel);
                    re.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            if (!priceTF.getText().equals("") && Double.parseDouble(priceTF.getText()) > N2[0]) {
                                for (int row = 0; row < rowCount; row++) {
                                    Sale sale = new Sale();
                                    sale.setId(model.getValueAt(row, 0).toString() + currentDate.getMonthValue());
                                    sale.setName(model.getValueAt(row, 1).toString());
                                    sale.setAmount((Double) model.getValueAt(row, 2));
                                    sale.setQuantity((Integer) model.getValueAt(row, 3));
                                    sale.setTime(currentDate.getMonthValue());
                                    Sale add_sale = mySQL_Sale.getSaleByIP(sale.getId());
                                    if(add_sale == null){
                                        mySQL_Sale.addSale(sale);
                                    }else{
                                        sale.setQuantity(sale.getQuantity() + add_sale.getQuantity());
                                        mySQL_Sale.updateSale(sale);
                                    }
                                }
                                double money = Double.parseDouble(priceTF.getText()) - N2[0];
                                model.setRowCount(0);
                                hint.setText("……");
                                N1[0] = 0;
                                N2[0] = 0;
                                piecesNumber.setText("件数：" + N1[0]);
                                total.setText("合计：" + N2[0] + "元");
                                JOptionPane.showMessageDialog(panel, "找零：" + money + "元");
                                dialog.dispose();
                            }else {
                                JOptionPane.showMessageDialog(panel, "输入金额不足！");
                            }
                        }
                    });
                    dialog.setVisible(true);
                }
            }
        });

        return  checkoutPanel;
    }

    private JPanel createProductPanel() {
        productPanel.setLayout(new GridLayout(2,1,0,0));
        JPanel product_1 = new JPanel();
        JButton add = new JButton("添加新商品");
        JLabel product = new JLabel("商品名：");
        JTextField productTF = new JTextField(20);
        JButton query =  new JButton("查询");
        JButton modify = new JButton("修改");

        product_1.add(add);
        product_1.add(product);
        product_1.add(productTF);
        product_1.add(query);
        product_1.add(modify);

        String[] columns = {"商品编号", "商品名称", "售价", "数量"};
        DefaultTableModel model = new DefaultTableModel(columns, 0) {
            @Override
            public Class<?> getColumnClass(int columnIndex) {
                switch (columnIndex) {
                    case 0: return String.class;  // 商品编号
                    case 1: return String.class;  // 商品名称
                    case 2: return Double.class;  // 价格
                    case 3: return Integer.class; // 数量
                    default: return Object.class;
                }
            }
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        List<Product> products = mySQL_Product.getAllProduct();
        if(products!=null){
            products.forEach(pro ->{
                model.addRow(pro.toArray());
            });
        }

        JTable table = new JTable(model);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane scrollPane = new JScrollPane(table);

        productPanel.add(product_1);
        productPanel.add(scrollPane);

        add.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JDialog dialog = new JDialog(frame, "添加商品", true);
                JPanel panel = new JPanel();
                JTextField nameTF = new JTextField(12);
                JTextField priceTF = new JTextField(12);
                JTextField amountTF = new JTextField(12);
                JButton add = new JButton("确认增加");
                dialog.setBounds(700, 200, 300, 400);

                dialog.setLayout(new FlowLayout(FlowLayout.CENTER,0,50));
                panel.setLayout(new GridLayout(3,2,0,20));
                panel.add(new JLabel("商品名称："));
                panel.add(nameTF);
                panel.add(new JLabel("商品价格："));
                panel.add(priceTF);
                panel.add(new JLabel("商品数量："));
                panel.add(amountTF);
                dialog.add(panel);
                dialog.add(add);
                add.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        if(nameTF.getText()!=null&&priceTF.getText()!=null&&amountTF.getText()!=null
                        &&!nameTF.getText().equals("")&&!priceTF.getText().equals("")&&!amountTF.getText().equals("")){
                            if(isDouble(priceTF.getText())&&isInteger(amountTF.getText())){
                                Product product = new Product();
                                String id = products.getLast().getId();
                                int temp = Integer.parseInt(id) % 100000 + 1;
                                LocalDate today = LocalDate.now();
                                int year = today.getYear();
                                int month = today.getMonthValue();
                                int id1 = (year % 100) * 1000000 + month * 10000 + temp;
                                product.setId(Integer.toString(id1));
                                product.setName(nameTF.getText());
                                product.setPrice(Double.parseDouble(priceTF.getText()));
                                product.setAmount(Integer.parseInt(amountTF.getText()));
                                mySQL_Product.addProduct(product);

                                dialog.dispose();
                                model.setRowCount(0);

                                List<Product> products = mySQL_Product.getAllProduct();
                                if(products!=null){
                                    products.forEach(pro ->{
                                        model.addRow(pro.toArray());
                                    });
                                }
                            }else {
                                JOptionPane.showMessageDialog(panel, "增加商品失败：格式不规范！");
                            }
                        }
                    }
                });
                dialog.setVisible(true);
            }
        });

        query.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if(productTF.getText()!=null && !productTF.getText().equals("")){
                    Product product = mySQL_Product.getProductByName(productTF.getText());
                    if(product!=null){
                        model.setRowCount(0);
                        model.addRow(product.toArray());
                    }
                }else {
                    model.setRowCount(0);
                    List<Product> products_1 = mySQL_Product.getAllProduct();
                    products_1.forEach(pro -> {
                        model.addRow(pro.toArray());
                    });
                }
            }
        });
        modify.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int selectedRow = table.getSelectedRow();
                if (selectedRow != -1) {
                    int modelRow = table.convertRowIndexToModel(selectedRow);
                    Object product_1 = model.getValueAt(modelRow, 1);
                    Object product_2 = model.getValueAt(modelRow, 2);
                    Object product_3 = model.getValueAt(modelRow, 3);

                    JDialog dialog = new JDialog(frame, "修改商品", true);
                    JPanel panel = new JPanel();
                    JTextField nameTF = new JTextField(12);
                    nameTF.setText(product_1.toString());
                    JTextField priceTF = new JTextField(12);
                    priceTF.setText(product_2.toString());
                    JTextField amountTF = new JTextField(12);
                    amountTF.setText(product_3.toString());
                    JButton confirm = new JButton("确认修改");
                    JButton delete = new JButton("直接删除");
                    dialog.setBounds(700, 200, 300, 400);

                    dialog.setLayout(new FlowLayout(FlowLayout.CENTER,0,50));
                    panel.setLayout(new GridLayout(4,2,0,20));
                    panel.add(new JLabel("商品名："));
                    panel.add(nameTF);
                    panel.add(new JLabel("商品价格："));
                    panel.add(priceTF);
                    panel.add(new JLabel("商品数量："));
                    panel.add(amountTF);
                    panel.add(confirm);
                    panel.add(delete);
                    dialog.add(panel);
                    confirm.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            Product p1 = mySQL_Product.getProductByName(product_1.toString());
                            p1.setName(nameTF.getText());
                            p1.setPrice(Double.parseDouble(priceTF.getText()));
                            p1.setAmount(Integer.parseInt(amountTF.getText()));
                            mySQL_Product.updateProduct(p1);
                            dialog.dispose();
                            model.setValueAt(nameTF.getText(), modelRow, 1);
                            model.setValueAt(Double.parseDouble(priceTF.getText()), modelRow, 2);
                            model.setValueAt(Integer.parseInt(amountTF.getText()), modelRow, 3);
                        }
                    });
                    delete.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            Product p1 = mySQL_Product.getProductByName(product_1.toString());
                            mySQL_Product.deleteProduct(p1);
                            dialog.dispose();
                            model.setRowCount(0);

                            List<Product> products = mySQL_Product.getAllProduct();
                            if(products!=null){
                                products.forEach(pro ->{
                                    model.addRow(pro.toArray());
                                });
                            }
                        }
                    });

                    dialog.setVisible(true);
                }else{
                    JOptionPane.showMessageDialog(product_1, "请先选择要删除的行！");
                }

            }
        });
        return  productPanel;
    }

    private static boolean isInteger(String str) {
        try {
            Integer.parseInt(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }
    private static boolean isDouble(String str) {
        try {
            Double.parseDouble(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    private JPanel createUserPanel() {
        userPanel.setLayout(new GridLayout(2,1,0,0));
        JPanel user_1 = new JPanel();
        JLabel User = new JLabel("用户名：");
        JTextField UserTF = new JTextField(20);
        JButton query = new JButton("查询");
        JButton resetUser = new JButton("注销用户");
        user_1.add(User);
        user_1.add(UserTF);
        user_1.add(query);
        user_1.add(resetUser);

        String[] columns = {"账号", "密码"};
        DefaultTableModel model = new DefaultTableModel(columns, 0) {
            @Override
            public Class<?> getColumnClass(int columnIndex) {
                switch (columnIndex) {
                    case 0: return String.class;
                    case 1: return String.class;
                    default: return Object.class;
                }
            }
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        List<User> allUser = mySQL_User.getAllUser();

        allUser.forEach(user -> {
            model.addRow(user.toArray());
        });

        JTable table = new JTable(model);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane scrollPane = new JScrollPane(table);

        userPanel.add(user_1);
        userPanel.add(scrollPane);

        query.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if(UserTF.getText() != null && !UserTF.getText().equals("")) {
                    User user = mySQL_User.getUserByIP(UserTF.getText());
                    if (user != null) {
                        model.setRowCount(0);
                        model.addRow(user.toArray());
                    }
                }else {
                    model.setRowCount(0);
                    List<User> allUser_1 = mySQL_User.getAllUser();
                    allUser_1.forEach(user -> {
                        model.addRow(user.toArray());
                    });
                }
            }
        });
        resetUser.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int selectedRow = table.getSelectedRow();
                if (selectedRow != -1) {
                    int modelRow = table.convertRowIndexToModel(selectedRow);
                    Object UserName = model.getValueAt(modelRow, 0);

                    int confirm = JOptionPane.showConfirmDialog(
                            user_1,
                            "确定要删除用户: " + UserName + " 吗？",
                            "确认删除",
                            JOptionPane.YES_NO_OPTION
                    );

                    if (confirm == JOptionPane.YES_OPTION) {
                        boolean i = mySQL_User.deleteUser(mySQL_User.getUserByIP(UserName.toString()));
                        if (i == true) {
                            JOptionPane.showMessageDialog(user_1, "删除成功！");
                        }else {
                            JOptionPane.showMessageDialog(user_1, "删除失败！");
                        }
                    }
                } else {
                    JOptionPane.showMessageDialog(user_1, "请先选择要删除的行！");
                }
            }
        });
        return   userPanel;
    }
    private JPanel createSalesPanel() {
        salesPanel.setLayout(new GridLayout(2,1,0,0));
        JPanel panel = new JPanel();


        String[] week_ = {"本月", "上月"};
        JComboBox<String> week = new JComboBox<>(week_);

        String[] columns = {"商品编号", "商品名称", "售价", "销量"};
        DefaultTableModel model = new DefaultTableModel(columns, 0) {
            @Override
            public Class<?> getColumnClass(int columnIndex) {
                switch (columnIndex) {
                    case 0: return String.class;  // 商品编号
                    case 1: return String.class;  // 商品名称
                    case 2: return Double.class;  // 价格
                    case 3: return Integer.class; // 数量
                    default: return Object.class;
                }
            }
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        JTable table = new JTable(model);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane scrollPane = new JScrollPane(table);
        panel.add(week);
        salesPanel.add(panel);
        salesPanel.add(scrollPane);

        week.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String selected = (String) week.getSelectedItem();
                LocalDate currentDate = LocalDate.now();
                int current = currentDate.getMonthValue();
                List<Sale> allSale = mySQL_Sale.getAllSale();
                System.out.println(currentDate.getMonthValue());
                if(selected == "本月"){
                    model.setRowCount(0);
                    allSale.forEach(sale -> {
                        if(sale.getTime() == current) {
                            model.addRow(sale.toArray());
                        }
                    });
                }else if(selected == "上月"){
                    model.setRowCount(0);
                    allSale.forEach(sale -> {
                        if(current == 1) {
                            if(sale.getTime() == 12) {
                                model.addRow(sale.toArray());
                            }
                        }else{
                            if(sale.getTime() == current - 1) {
                                model.addRow(sale.toArray());
                            }
                        }
                    });
                }
            }
        });
        return  salesPanel;
    }

    private void setupListeners(){
        checkoutButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                cardLayout.show(cardPanel, "checkout");
            }
        });
        productButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                cardLayout.show(cardPanel, "product");
            }
        });
        userButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                cardLayout.show(cardPanel, "user");
            }
        });
        salesButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                cardLayout.show(cardPanel, "sales");
            }
        });
        exitButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int result = JOptionPane.showConfirmDialog(
                        cardPanel,
                        "确定要退出登录吗？",
                        "确认退出",
                        JOptionPane.YES_NO_OPTION
                );

                if (result == JOptionPane.YES_OPTION) {
                    container.removeAll();
                    frame.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 250));
                    container.add(login.GetPanel());
                    container.revalidate();
                    container.repaint();
                    frame.setVisible(true);
                }
            }
        });
    }
}
